import axios from 'axios'
import store from '@/store'
import router from "@/router"
import qs from 'qs'
import { Message, Loading } from 'element-ui'
import { getToken } from '@/utils/auth'
import { tansParams, blobValidate } from "@/utils/index";
import { saveAs } from 'file-saver';

let downloadLoadingInstance;
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// create an axios instance
const service = axios.create({
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 60 // request timeout
})


service.interceptors.request.use(
  config => {
    const token = getToken()
    config.headers['Authorization'] = token || ''
    config.headers['appKey'] = window.$setting.appKey;
    config.baseURL = window.$setting.baseUrl;
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use( response => {
    try {
      // 二进制数据则直接返回
      if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
        return response
      }

      const res = response.data
      // console.log("------------请求成功------------\n", res)
      if (res && res.code == 1) {
        return res
      } else if (res && res.code == 2) {
        Message({
          message: res.msg || "登录已过期!",
          type: 'error',
          duration: 5 * 1000
        })
        store.dispatch('fedLogOut')
        // 如果在非登录页，发现登录过期时，跳转登录页面，并携带参数
        if (router.currentRoute.path != '/login') {
          router.push({
            path: '/login',
            query: {
              redirect: location.hash.replace('#', '')
            }
          })
          window.location.reload()
        }
        return Promise.reject(new Error(res.msg || 'Error'))
      } else {
        Message({
          message: res.msg || '请求出错!',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.msg || 'Error'))
        // return new Error(res.msg || 'Error')
      }
    } catch (error) {
      console.log("捕获异常：", error)
    }
  },
  error => {
    Message({
      message: error.message || "系统异常！",
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)


function getFile(f) {
  let obj = {}
  f.forEach(item => {
    if (item.indexOf('=') > -1) {
      const arr = item.split("=")
      obj[arr[0]] = arr[1]
    }
  })
  return obj['filename']
}

// 通用下载方法
export function download1(url, params={}, filename, config) {
  downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  })
  return service.post(url, params, {
    transformRequest: [(params) => {
      return tansParams(params)
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'blob',
    ...config
  }).then(async (res) => {
    const data = res.data;
    const f = decodeURI(res.headers['content-disposition']).split(";");
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, getFile(f) || filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      Message.error(rspObj.msg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}


export function download(url, params={},method="post", filename='1.xlsx') {
    delete params.page;
    delete params.pageSize;
    return new Promise((resolve, reject) => {
      const config = {
        url,
        method,
        responseType: 'blob',
        timeout: 5*60*1000,
      }
      if(method=='post') {
        config.body = params
      }
      if(method == 'get') {
        config.url = url +'?'+ qs.stringify(params, { indices: false })
      }
      service(config).then(async (res) => {
        const f= decodeURI(res.headers['content-disposition']).split(";");
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          saveAs(blob, getFile(f))
          resolve('ok')
        } else {
          Message.error('下载文件出现错误，请联系管理员。');
          reject('error')
        }
      }).catch((r) => {
        reject('error')
        console.error(r)
        Message.error('下载文件出现错误，请联系管理员！')
      })
    })
  }
export default service
